package com.ming.stringstudy.feedbacksystem.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ming.stringstudy.feedbacksystem.pojo.Result;
import com.ming.stringstudy.feedbacksystem.utils.HeaderName;
import com.ming.stringstudy.feedbacksystem.utils.JwtUtils;
import com.ming.stringstudy.feedbacksystem.utils.PermissionConstants;
import com.ming.stringstudy.feedbacksystem.utils.PermissionUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * 专门为 查看与该用户有关的所以问题/意见列表接口做的拦截器
 * 功能：保证低权限的用户不要越级查询,强制注入自己的部门/自己的id
 */
@Slf4j
@Component
public class CommentPageInterceptor implements HandlerInterceptor {
    @Autowired
    private PermissionUtils permissionUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取权限id
        Integer roleId = (Integer) JwtUtils.parserJwt(request.getHeader(HeaderName.headerName)).get("roleId");
        if(request.getMethod().equals("GET")){
            // 必须有基础查询权限
            if (permissionUtils.equalPermission(roleId,PermissionConstants.REPLY_VIEW)){
                permissionState(request,roleId);
            }else{
                response.getWriter().write(JSONObject.toJSONString(Result.error("permission denied")));
                return false;
            }
        }
        return true;
    }

    private void permissionState(HttpServletRequest request,Integer roleId) throws IOException {
        // 解析数据
        String userId = request.getParameter("userId");
        String deptId = request.getParameter("deptId");
        // 获取令牌的用户Id
        String JwtUserId = JwtUtils.parserJwt(request.getHeader(HeaderName.headerName)).get("id").toString();
        // 获取令牌的部门Id
        String JwtDeptId = JwtUtils.parserJwt(request.getHeader(HeaderName.headerName)).get("deptId").toString();
        log.info("userId:{}",userId);
        log.info("deptId:{}",deptId);
        // 是否有校领导权限
        if(permissionUtils.equalPermission(roleId, PermissionConstants.SCHOOL_STATISTICS_VIEW)){
            if(userId == null){
                userId = "";
            }else if(userId.equals(JwtUserId)){
                // 查自己的问题
                userIdAutowired(request, JwtUserId,deptId);
                return;
            }
            if(deptId == null){
                deptId = "";
            }
            request.setAttribute("userId",userId);
            request.setAttribute("deptId",deptId);
        }else if(permissionUtils.equalPermission(roleId,PermissionConstants.DEPARTMENT_STATISTICS_VIEW)){
            // 没有全校查询权限只能查自己部门及自己的全部信息
            // 都为空默认为查询自己部门所有有关问题
            if(userId == null){
                request.setAttribute("deptId",JwtDeptId);
                request.setAttribute("userId","");
                log.info("没有全校查询权限，只能查自己的部门Id:{}，自动注入",JwtDeptId);
            }else if(userId.equals(JwtUserId)){
                // 查自己的问题
                userIdAutowired(request,JwtUserId,deptId);
            }else{
                // 查与自己部门中，某某同学的提问
                request.setAttribute("deptId",JwtDeptId);
                request.setAttribute("userId",userId);
                log.info("自动注入，自己部门");
            }
        }else { // 只有回复查询的权限
            userIdAutowired(request,JwtUserId,deptId);
        }
    }

    /**
     * 注入账户自己的id
     * @param request
     * @param deptId
     */
    private static void userIdAutowired(HttpServletRequest request,String JwtUserId, String deptId) {
        // 只能查询自己的全部信息
        request.setAttribute("userId", JwtUserId);
        if(deptId == null){
            deptId = "";
        }
        request.setAttribute("deptId", deptId);
        log.info("查询自己的userId:{}，自动注入",JwtUserId);
    }
}
